extends sympy
extends pyspice

snippet utf     "file format"
# -*- coding:utf-8 -*-
endsnippet

snippet try "try...except...else"
try:
    $1
except:
    $2
else:
    $3
endsnippet

snippet finally "try...finally"
try:
    $1
finally:
    $2
endsnippet

snippet init    "class initial"
def __init__(self, ${1:parameter}):
    ${3:self.name = parameter}
    return ${4:#value}
endsnippet

snippet class   "class template"
# 如果子类定义了构造函数，而没有调用父类构造函数
# 将不具备父类的所有属性（包括使用到父类属性的父类方法）
class ${1:name} (${2:object}):
    #def __init__(self, name):  #构造方法
        #object.__init__(self)  # 方法一
        #super($1, self).__init__() # 方法二
        #self.name = name

    $3
endsnippet

snippet lambda
lambda ${1:var} : ${2:expression}
endsnippet

snippet main
if __name__ == '__main__':
    ${1:main()}
endsnippet
###################################function#####################################

snippet open    "open large file by useing read(n) function"
def read_in_chunks(f, chunk_size=2048):
    while True:
        data = f.read(chunk_size)  # 每次读取指定的长度
        if not data:
            break
        yield data


with open(${1:filename}, 'r', encoding='utf-8') as f:
    for chuck in read_in_chunks(f):
        ${2:#do_something(chunk)}
endsnippet

snippet solution "the template of leetcode" b
from typing import List
class Solution:
    $1

s = Solution()
endsnippet

#########################pyqt5#########################
snippet pyqt_widget "QWidget"
#-*- coding:utf-8 -*-
#from PyQt5.QtGui import *
from PyQt5.QtCore import pyqtSignal, pyqtSlot
from PyQt5.QtWidgets import QApplication, QWidget, QTextEdit, QVBoxLayout

class PyQt5_Temp(QWidget):
    signalTemp = pyqtSignal([str])
    #self.signalTemp.emit('temp')
    def __init__(self):
        super(PyQt5_Temp, self).__init__()
        self.initUI()

        #self.tempBtn.clicked.connect(self.tempSlot)

    def initUI(self):
        self.text = QTextEdit()

        mainLayout = QVBoxLayout()
        mainLayout.addWidget(self.text)

        self.setLayout(mainLayout)

        self.setWindowTitle('PyQt5_Temp')

    @pyqtSlot()
    def tempSlot(self):
        #code
        return #value

if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)

    ui = PyQt5_Temp()
    ui.show()
    #ui.setStyleSheet(style)
    sys.exit(app.exec_())
endsnippet

snippet tcp_server "simple tcp server example" b
#-*- coding: UTF-8 -*- 
import argparse
import socket

parser = argparse.ArgumentParser(description="simple tcp server program")
parser.add_argument("--ip", default="127.0.0.1", help="tcp server ip address")
parser.add_argument("--port", default=8888, type=int, help="tcp server port")
args = parser.parse_args()

server = socket.socket()
server.bind((args.ip, args.port))
server.listen(5)
while True:
    print ("wait for new tcp client to connect...")
    connection, addr = server.accept()
    print ('new client addr is : {0}'.format(addr))
    
    while True:
        data = connection.recv(1024)
        if not data:
            print ("client actively disconnects the socket")
            break
        print(data)
    connection.close() 
endsnippet

snippet tcp_client "simple tcp client example" b
#-*- coding: UTF-8 -*-
import argparse
import socket
import time

parser = argparse.ArgumentParser(description="simple tcp client program")
parser.add_argument("--ip", default="127.0.0.1", help="remote tcp server ip address")
parser.add_argument("--port", default=8888, type=int, help="remote tcp client port")
parser.add_argument("-t", "--timeout", default=0, type=int, help="tcp client timeout")
args = parser.parse_args()

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((args.ip, args.port))


if args.timeout == 0:
    client.settimeout(None)
else:
    client.settimeout(args.timeout)

while True:
    try:
        data = client.recv(2048)

    except socket.timeout:
        print("There are no data in {0}s. Close socket.".format(args.timeout))
        client.close()
        break;
endsnippet


snippet plot "simple plot template" b
fig, ax = plt.subplots(2, 1, sharex=True)

ax[0].plot(ch0, label="ch0")
ax[0].set_title("title")
ax[0].set_xlabel("x-label", fontsize=20)
ax[0].set_ylabel("y-label", fontsize=15)
ax[0].text(0, ch0.mean(), "text", fontsize=20)
ax[0].annotate('annotate', xy=(x, y), xytext=(x+1, y+1), arrowprops=dict(facecolor='black', shrink=0.05))
ax[0].grid(True)
ax[0].legend()
plt.show()
endsnippet

snippet log "simple log template" b
import logging

LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s"
DATE_FORMAT = "%m/%d/%Y %H:%M:%S %p"
logging.basicConfig(filename='my.log', level=logging.DEBUG, format=LOG_FORMAT, datefmt=DATE_FORMAT)
endsnippet

snippet argparse "simple argparse template" b
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("file", help="${1:help}")
parser.add_argument("-c", "--count", default=10000, type=int, help="set cycle numbers that send the same context")
parser.add_argument("-v", "--verbose", action='store_true', help="verbose")
args = parser.parse_args()
endsnippet


snippet udp_client "simple udp client example" b
import socket

address = ('127.0.0.1', 6666)  # udp server的IP地址和端口号
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

packet = "wangjun"
s.sendto(str.encode(packet), address)
endsnippet

snippet udp_server "simple udp server example"
import socket

address = ("192.168.1.166", 6666)  # 本机的IP地址和端口号
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(address)

while True:
    data, addr = sock.recvfrom(1024)
    print("Receive data = %s" % data)
endsnippet
